<template>
    <a-form ref='formRef' :label-col='{span : 5}' :model='formData'>
        <a-form-item style='display:none' name='id'>
            <a-input type='hidden' v-model:value='formData.id' />
        </a-form-item>
        <a-form-item label='名称' name='name' :rules="[{required : true, message : '请填写名称'}]">
            <a-input type='text' v-model:value='formData.name' :maxlength="20" show-count  />
        </a-form-item>
        <a-form-item label='参数名' name='key' :rules="[{required : true, message : '请填写参数名'}]">
            <a-input type='text' v-model:value='formData.key' :maxlength="20" show-count  />
        </a-form-item>
        <a-form-item label="输入控件" name='inputType' :rules="[{required : true, message : '请选择输入控件'}]">
            <a-select v-model:value='formData.inputType' :options='inputTypes'></a-select>
        </a-form-item>
        <a-form-item label='单位' name='unit'>
            <a-input type='text' v-model:value='formData.unit' :maxlength="20" show-count  />
        </a-form-item>
        <a-form-item label="选项" name="options" v-if="formData.inputType == 'select'">
            <Codemirror v-model:value="formData.options" name="options" height="200" @change="changeFunc" :options="{mode : 'text/javascript', theme : '3024-night'}"></Codemirror>
            <div>示例：[{"label" : "年龄", "value" : 32}]</div>
        </a-form-item>
        <a-form-item label='启用' name='enable'>
            <a-switch v-model:checked='formData.enable' checked-children='启用' un-checked-children='禁用'/>
        </a-form-item>
    </a-form>
</template>

<script lang="ts" setup>
    import { saveApi, uploadApi } from '@/api/devices/DeviceParamsField';
    import { ref } from 'vue';
    import "codemirror/mode/javascript/javascript.js"
    import "codemirror/theme/3024-night.css"
    import Codemirror from "codemirror-editor-vue3"

    const props = defineProps<{
        row? : any;
    }>()

    const inputTypes = [
        {value : 'number', label : 'number'},
        {value : 'select', label : 'select'},
        {value : 'text', label : 'input'},

    ]

    const formRef = ref()

    
    const formData = ref({
        id : 0,
        name : '',
        key : '',
        inputType : '',
        options : '',
        unit : '',
        enable : true

    })

    if(props.row) {
        for(let k in props.row) {
            if(k in formData.value) {
                formData.value[k] = props.row[k]
            }
        }
    }

    function changeFunc(e) {
        formData.value.options = e
    }

    async function submit() {
        let params  = await formRef.value.validate()
        if(params.inputType == 'select') {
            params.options = JSON.parse(params.options)
        }

        return saveApi(params)
    }



    defineExpose({
        submit
    })
</script>